package com.gombe.credit.app.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.graphics.Typeface
import android.os.CountDownTimer
import android.view.View
import android.widget.LinearLayout
import com.gombe.credit.app.R
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.configs.GombeCreditConfigs
import com.gombe.credit.app.databinding.ActGombeCreditApplyBinding
import com.gombe.credit.app.databinding.ActGombeCreditApplyDetailsChildItemBinding
import com.gombe.credit.app.databinding.ActGombeCreditApplyDetailsItemBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.event.GombeCreditEventPointType
import com.gombe.credit.app.event.room.GombeCreditPointManager
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.utils.GombeCreditDensityUtil
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.helper.GombeCreditProcessHelper
import com.gombe.credit.app.weight.seekbar.OnRangeChangedListener
import com.gombe.credit.app.weight.seekbar.RangeSeekBar
import com.gombe.credit.lib.adapter.GombeCreditOnSingleClickListener
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal


/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/9/25 19:21
 * @Annotation：申请贷款
 */
class ActGombeCreditApply: CommonActivity() {
    lateinit var binding: ActGombeCreditApplyBinding
    private var countdownTimer: MyCountDownTimer? = null
    //等待时长
    private var countdown = 10 * 60
    //选择的申贷时长
    private var daysList = arrayListOf<String>()
    private var selectedDays = ""
    //埋点备注
    var eventRemark = "LoanApply Page"

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, ActGombeCreditApply::class.java)
            context.startActivity(intent)
        }
    }

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditApplyBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setGombeCreditRootParentBackgroundColor(getColor(R.color.white))
        setGombeCreditTitleBarVisibility(View.VISIBLE)
        setGombeCreditTextTitle(getString(R.string.gombe_credit_apply_title))
        setGombeCreditTextTitleColor(getColor(R.color.black))
        setGombeCreditBackBtnRes(R.mipmap.gombe_credit_image_back_black_icon)
        setGombeCreditRightBtnRes(R.mipmap.gombe_credit_image_customer_black_icon)

        initGombeCreditApplyRefreshLayout()
        binding.applyContentLayout.visibility = View.GONE
        binding.btnApplySubmit.isEnabled = false

        val boldTypeface = Typeface.createFromAsset(assets,"fonts/Lexend-Bold.ttf")
        binding.applyDaysSeekBar.setTypeface(boldTypeface)
    }

    override fun initGombeCreditListener() {
        //客服
        rootViewBinding.rootCustomer.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                showCustomerDialog(eventRemark)
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER,eventRemark)
            }
        })

        /**
         * 申贷额度选择
         */
        binding.applyAmountSeekBar.setOnRangeChangedListener(object : OnRangeChangedListener {
            override fun onRangeChanged(view: RangeSeekBar?, leftValue: Float, rightValue: Float, isFromUser: Boolean) {
            }
            override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
            }
            override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
                val leftSeekBar = view?.leftSeekBar
                leftSeekBar?.let {
                    binding.textApplyLoanAmount.text = it.indicatorTextDecimalFormat.format(it.progress)
                }
                loadGombeCreditApplyDetailsAction()
            }
        })

        /**
         * 申贷时长选择
         */
        binding.applyDaysSeekBar.setOnRangeChangedListener(object : OnRangeChangedListener {
            override fun onRangeChanged(view: RangeSeekBar?, leftValue: Float, rightValue: Float, isFromUser: Boolean) {
            }
            override fun onStartTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
            }
            override fun onStopTrackingTouch(view: RangeSeekBar?, isLeft: Boolean) {
                val leftSeekBar = view?.leftSeekBar
                leftSeekBar?.let {
                    val leftIndex = (it.progress * (daysList.size - 1)).toInt()
                    selectedDays = daysList[leftIndex]
                }
                loadGombeCreditApplyDetailsAction()
            }
        })

        //提交
        binding.btnApplySubmit.setOnClickListener(object : GombeCreditOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_CLICK.LOAN_APPLY_SUBMIT,eventRemark)
                // TODO: 申贷页提交按钮 需上报所有埋点
                GombeCreditPointManager.getInstance().manualReport()

                showGombeCreditLoading()
                submitGombeCreditApplyAction()
            }
        })
    }

    override fun takeGombeCreditData() {
        showGombeCreditLoading()
        loadGombeCreditApplyDetailsAction()
    }

    /* 初始化刷新 */
    private fun initGombeCreditApplyRefreshLayout() {
        binding.applyRefreshLayout.setColorSchemeResources(R.color.theme,R.color.purple_500)
        binding.applyRefreshLayout.setOnRefreshListener {
            loadGombeCreditApplyDetailsAction()
        }
    }

    /**
     * 获取贷款金额
     */
    private fun takeGombeCreditApplyAmount(): String {
        return binding.textApplyLoanAmount.text.toString()
    }

    /**
     * 获取贷款期限
     */
    private fun takeGombeCreditApplyDays(): String {
        return selectedDays
    }

    /**
     * 不可选择贷款额度
     */
    fun showGombeCreditApplyNotOptionalViews(data: JSONObject) {
        //最小可选额度
        val minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString()
        //最大值为剩余额度
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //显示额度
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        //颗粒度
        val scale = data.optString("granularity","1000")
        if (minAmount.toFloat() >= maxAmount.toFloat()){
            //最大值必须要比最小值大
            binding.applyAmountSeekBar.setRange(maxAmount.toFloat() - scale.toFloat(),maxAmount.toFloat())
        } else {
            binding.applyAmountSeekBar.setRange(minAmount.toFloat(),maxAmount.toFloat())
        }
        binding.applyAmountSeekBar.setIndicatorTextDecimalFormat(scale)//刻度
        binding.applyAmountSeekBar.setProgress(amount.toFloat())

        binding.textMinAmount.text = minAmount
        binding.textMaxAmount.text = maxAmount

        //禁止滑动
        binding.applyAmountSeekBar.isEnabled = false
        binding.applyAmountSeekBar.leftSeekBar?.setThumbDrawableId(R.mipmap.gombe_credit_image_apply_loan_amount_seekbar_thumb_normal)
    }

    /**
     * 允许选择贷款额度
     */
    fun showGombeCreditApplyOptionalViews(data: JSONObject) {
        //最小可选额度
        var minAmount = BigDecimal(data.optString("minAmount")).stripTrailingZeros().toPlainString()
        //最大值为剩余额度
        val maxAmount = BigDecimal(data.optString("maxAmount")).stripTrailingZeros().toPlainString()
        //显示额度
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        //颗粒度
        val scale = data.optString("granularity","1000")
        if (minAmount.toFloat() >= maxAmount.toFloat()){
            minAmount = "${maxAmount.toFloat() - scale.toFloat()}"
        }
        binding.applyAmountSeekBar.setIndicatorTextDecimalFormat(scale)//刻度
        //最大值必须要比最小值大
        binding.applyAmountSeekBar.setRange(minAmount.toFloat(),maxAmount.toFloat())
        binding.applyAmountSeekBar.setProgress(amount.toFloat())

        binding.textMinAmount.text = BigDecimal(minAmount).stripTrailingZeros().toPlainString()
        binding.textMaxAmount.text = maxAmount

        //支持滑动
        binding.applyAmountSeekBar.isEnabled = true
        binding.applyAmountSeekBar.leftSeekBar?.setThumbDrawableId(R.mipmap.gombe_credit_image_apply_loan_amount_seekbar_thumb)
    }

    /**
     * 设置贷款明细
     */
    fun showGombeCreditApplyDetailsList(data: JSONObject) {
        binding.applyContentLayout.visibility = View.VISIBLE
        binding.btnApplySubmit.isEnabled = true
        startGombeCreditApplyCountdownTimer()

        //去掉末尾的0
        val amount = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        binding.textApplyLoanAmount.text = amount
        binding.textApplyCurrency.text = data.optString("currency")

        //明细
        val array = data.optJSONArray("detailItemList")
        val detailItemList = arrayListOf<JSONObject>()
        if (array != null){
            for (i in 0..<array.length()){
                val item = array.optJSONObject(i)
                if (item.has("title") && item.optString("title") == "YES"){
                    detailItemList.add(item)
                }
            }
            for (i in 0..<detailItemList.size){
                val obj = detailItemList[i]
                val childArray = JSONArray()
                var isAddChild = false
                for (n in 0..<array.length()){
                    val item = array.optJSONObject(n)
                    if (obj.optString("showName") == item.optString("showName")){
                        isAddChild = true
                        childArray.put(item)
                        continue
                    }
                    if (item.has("title") && item.optString("title") == "YES"){
                        isAddChild = false
                        continue
                    }
                    if (isAddChild){
                        childArray.put(item)
                    }
                }
                obj.put("childList",childArray)
            }
        }

        val boldTypeface = Typeface.createFromAsset(assets,"fonts/Lexend-Bold.ttf")
        binding.applyDetailsLayout.removeAllViews()
        detailItemList.forEach {
            val itemBinding = ActGombeCreditApplyDetailsItemBinding.inflate(layoutInflater)
            val params = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)
            params.setMargins(0,0,0,GombeCreditDensityUtil.dp2px(16f))
            itemBinding.detailsItemLayout.layoutParams = params
            val childList = it.optJSONArray("childList")
            if (childList != null){
                for (i in 0..<childList.length()){
                    val childItem = childList.optJSONObject(i)
                    val childView = ActGombeCreditApplyDetailsChildItemBinding.inflate(layoutInflater)
                    childView.textDetailsTitle.text = childItem.optString("showName")
                    childView.textDetailsTitle.setTextColor(getColor(R.color.gombe_credit_ffa8a8a8))
                    childView.textDetailsValue.text = childItem.optString("showDetail")
                    childView.textDetailsValue.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                    childView.viewLine.visibility = View.GONE

                    if (childItem.has("title") && childItem.optString("title") == "YES"){
                        childView.textDetailsTitle.typeface = boldTypeface
                        childView.textDetailsTitle.setTextColor(getColor(R.color.gombe_credit_ff1d1e20))
                        childView.viewLine.visibility = View.VISIBLE
                    }
                    childView.textOldValue.visibility = View.GONE
                    if (childItem.has("oldDetail")){
                        childView.textOldValue.visibility = View.VISIBLE
                        childView.textOldValue.text = childItem.optString("oldDetail")
                    }
                    childView.discountLayout.visibility = View.GONE
                    if (childItem.has("discount")){
                        childView.discountLayout.visibility = View.VISIBLE
                        childView.textDiscount.text = childItem.optString("discount")
                    }
                    itemBinding.detailsItemLayout.addView(childView.root)
                }
            }
            binding.applyDetailsLayout.addView(itemBinding.root)
        }
    }

    /**
     * 设置贷款时长列表
     */
    private fun showGombeCreditApplyDaysList(data: JSONObject){
        if (daysList.size <= 0){
            //默认天数
            val defaultDays = data.optString("days")
            val daysArray = data.optJSONArray("daysArray")

            if (daysArray != null) {
                //如果daysArray中没有defaultDays，需要将defaultDays添加到daysArray列表中
                var isNeedAdd = true
                for (i in 0..<daysArray.length()){
                    if (daysArray.optString(i) == defaultDays){
                        isNeedAdd = false
                        break
                    }
                }
                if (isNeedAdd){
                    daysArray.put(0,defaultDays)
                }

                for (i in 0..<daysArray.length()){
                    val day = daysArray.optString(i)
                    daysList.add(day)
                }
            } else {
                daysList.add(defaultDays)
            }

            //设置显示刻度
            var showIndex = -1
            if (daysList.size <= 1){
                //禁止滑动
                binding.applyDaysSeekBar.isEnabled = false
                binding.applyDaysSeekBar.leftSeekBar?.setThumbDrawableId(R.mipmap.gombe_credit_image_apply_loan_amount_seekbar_thumb_normal)
                //手动再添加一条天数，防止报错
                daysList.add(defaultDays)
                showIndex = 1
            } else {
                binding.applyDaysSeekBar.isEnabled = true
                binding.applyDaysSeekBar.leftSeekBar?.setThumbDrawableId(R.mipmap.gombe_credit_image_apply_loan_amount_seekbar_thumb)
                showIndex = daysList.indexOf(defaultDays)
            }
            binding.applyDaysSeekBar.steps = daysList.size - 1
            binding.applyDaysSeekBar.tickMarkTextArray = daysList.toTypedArray()
            binding.applyDaysSeekBar.isStepsAutoBonding = true

            if (showIndex != -1){
                selectedDays = daysList[showIndex]
                val initProgress = (showIndex / (daysList.size - 1).toFloat())
                binding.applyDaysSeekBar.setProgress(initProgress)
            }
        }
    }

    /**
     * 贷款申请成功
     */
    fun showGombeCreditApplySuccess() {
        //刷新产品列表
        publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_PRODUCT_REFRESH))
        hideGombeCreditLoading()

        //是否包含SMS权限
        val permissionList = GombeCreditConfigsHelper.takeGombeCreditPermissionsList()
        if (permissionList.contains(Manifest.permission.READ_SMS)){
            //进入SMS权限使用说明页面
            onIntent(ActGombeCreditApplyWait::class.java)
        } else {
            //刷新主流程
            publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH))
        }
        finish()
    }

    /**
     * 申请失败 订单状态 或 申请状态 验证不通过，需要返回首页显示对应页面
     */
    fun showGombeCreditLoanApplyFailed() {
        hideGombeCreditLoading()
        finish()
    }

    override fun hideGombeCreditLoading() {
        super.hideGombeCreditLoading()
        binding.applyRefreshLayout.isRefreshing = false
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> {
                //需要校验 WhatsApp 或 SMS
                if (GombeCreditProcessHelper.isGombeCreditCheckWhatsApp() || GombeCreditProcessHelper.isGombeCreditCheckSMS()){
                    ActGombeCreditVerifyMobile.start(this)
                }
                finish()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_NET_ERROR -> {
                hideGombeCreditLoading()
            }
            else -> {

            }
        }
    }

    /**
     * 开启倒计时
     */
    private fun startGombeCreditApplyCountdownTimer(){
        if (countdownTimer != null){
            countdownTimer?.cancel()
        }
        countdown = 10 * 60
        if (countdownTimer == null){
            countdownTimer = MyCountDownTimer(this, countdown.toLong() * 1000, 1000)
        }
        countdownTimer?.start()
    }

    /**
     * 显示状态
     */
    private fun showGombeCreditApplyCountdownText(){
        val seconds = countdown % 60
        val showSeconds = if (seconds < 10) "0$seconds" else "$seconds"
        val minutes = countdown / 60 % 60
        val showMinutes = if (minutes < 10) "0$minutes" else "$minutes"

        binding.textMinute1.text = showMinutes.toCharArray()[0].toString()
        binding.textMinute2.text = showMinutes.toCharArray()[1].toString()
        binding.textSecond1.text = showSeconds.toCharArray()[0].toString()
        binding.textSecond2.text = showSeconds.toCharArray()[1].toString()
    }

    private fun showGombeCreditApplyCountdownComplete(){
        loadGombeCreditApplyDetailsAction()
    }

    class MyCountDownTimer(private val act: ActGombeCreditApply, millisInFuture: Long, countDownInterval: Long): CountDownTimer(millisInFuture, countDownInterval) {
        override fun onTick(millisUntilFinished: Long) {
            // 这里每隔一段时间（定时器间隔）会被调用
            // 可以在这里更新UI，显示剩余时间
            act.countdown = (millisUntilFinished / 1000).toInt()
            act.showGombeCreditApplyCountdownText()
        }
        override fun onFinish() {
            // 倒计时完成时被调用
            act.showGombeCreditApplyCountdownComplete()
        }
    }

    /**
     * 获取贷款信息
     */
    private fun loadGombeCreditApplyDetailsAction(){
        val params = JSONObject().addCommonParams()
        params.put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_APPLY_CUSTOM_LIMIT_PATH)
        params.put("amount",takeGombeCreditApplyAmount())
        params.put("oldFlag","YES")
        if (GombeCreditConfigs.isGombeCreditSwahili()){
            params.put("localLanguage","YES")
        }
        val applyDays = takeGombeCreditApplyDays()
        if (applyDays.isNotEmpty()){
            params.put("days",applyDays)
        }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                if (obj != null) {
                    //是否允许修改申请金额，不允许修改则不显示Seekbar
                    val chooseAmountFlag = obj.optBoolean("chooseAmountFlag",false)
                    when(chooseAmountFlag){
                        true -> {//允许选择贷款额度
                            showGombeCreditApplyOptionalViews(obj)
                        }
                        else -> {//不允许选择贷款额度
                            showGombeCreditApplyNotOptionalViews(obj)
                        }
                    }
                    showGombeCreditApplyDaysList(obj)
                    showGombeCreditApplyDetailsList(obj)
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    /**
     * 创建贷款申请订单
     */
    private fun submitGombeCreditApplyAction(){
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_LOAN_APPLY_ORDER_CREATE_PATH)
            put("amount",takeGombeCreditApplyAmount())
            put("days",takeGombeCreditApplyDays())
        }
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                showGombeCreditApplySuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideGombeCreditLoading()
            }
        })
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_APPLY_START,eventRemark)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (countdownTimer != null){
            countdownTimer?.cancel()
            countdownTimer = null
        }
        addEventPointRequestAction(GombeCreditEventPointType.GOMBECREDIT_TRACK_PAGE.LOAN_APPLY_END,eventRemark)
    }
}